package com.gao.api.gate.quick.proto.server;

import com.gao.api.gate.quick.proto.config.HttpServerConfig;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;

/**
 * <p></p>
 *
 * @author gaoshuangwen
 * @since 2022/01/07 21:44
 */
public class HttpServer {

    private final ServerConfig httpServerConfig;

    private final ChannelInitializer<Channel> childChannelInitializer;

    private  EventLoopGroup boss;

    private  EventLoopGroup work;

    public HttpServer(ServerConfig httpServerConfig, ChannelInitializer<Channel> childChannelInitializer) {
        this.httpServerConfig = httpServerConfig;
        this.childChannelInitializer = childChannelInitializer;
    }
    public HttpServer(ServerConfig httpServerConfig) {
        this.httpServerConfig = httpServerConfig;
        this.childChannelInitializer = new HttpServerChannelInitializer();
    }

    public void start(){
        HttpServerBootstrap serverBootstrap = new HttpServerBootstrap(httpServerConfig,childChannelInitializer);
        this.boss = serverBootstrap.getBoss();
        this.work = serverBootstrap.getWork();
        try {
            ChannelFuture channelFuture = serverBootstrap.buildServerBootstrap();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            stop();
        }
    }

    private void stop() {
        boss.shutdownGracefully();
        work.shutdownGracefully();
    }

}
